package com.ktjiaoyu.mqrabbitmqproducer.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktjiaoyu.mqrabbitmqproducer.config.RabbitConfig;
import com.ktjiaoyu.mqrabbitmqproducer.mapper.MailLogMapper;
import com.ktjiaoyu.mqrabbitmqproducer.pojo.MailLog;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class MailTask {
    @Resource
    MailLogMapper mailLogMapper;
    @Resource
    RabbitTemplate rabbitTemplate;

    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask(){
        // 查询消息状态为0即正在投递中的，并且tryTime重试时间小于当前时间。
        QueryWrapper qw=new QueryWrapper<MailLog>();
        qw.eq("status", 0);
        qw.lt("tryTime", LocalDateTime.now());
        List<MailLog> list =mailLogMapper.selectList(qw);

        for (MailLog mailLog : list) {
            //判断是否尝试次数到3,代表发送失败，修改当前消息的status为2
            if(mailLog.getCount()>=3){
                mailLog.setStatus(2);
                mailLogMapper.updateById(mailLog);
            }else{
                //没到3，继续发送，并且修改状态
                mailLog.setCount(mailLog.getCount()+1);
                mailLog.setUpdateTime(LocalDateTime.now());
                mailLog.setTryTime(LocalDateTime.now().plusMinutes(1));
                mailLogMapper.updateById(mailLog);

                //重新发送消息
                String message = "恭喜您，注册成功！";
                rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME,RabbitConfig.ROUTINGKEY_EMAIL,
                        message,new CorrelationData(mailLog.getMsgId()));
            }
        }
    }
}
